<template>
  <div class="app-container">

    <el-table v-loading="loading" :data="orderList" type="expand">
      <el-table-column label="主键" align="center" prop="id" v-if="false" />

      <!-- <el-table-column label="订单编号" align="center" prop="orderSn" />
      <el-table-column label="下单用户" align="center" prop="userId" /> -->
      <el-table-column label="协议ID" align="center" prop="creativeId" />
      <el-table-column label="最小奖励百分比" align="center" prop="minPerStr">

        <!-- <template slot-scope="scope">
          <div style="display: flex; justify-content: left; align-items: center">
            <el-image :src="requestUrl + scope.row.mainImg" style="
                width: 140px;
                height: 100px;
                float: left;
                display: inline-block;
              " :preview-src-list="[requestUrl + scope.row.mainImg]" />
            <span style="
                width: 100%;
                text-align: left;
                box-sizing: border-box;
                padding-left: 5px;
              ">{{ scope.row.goodsName }}</span>
          </div>
        </template> -->
      </el-table-column>
      <el-table-column label="每轮增长百分比" align="center" prop="addPerStr" />
      <el-table-column label="最大奖励百分比" align="center" prop="maxPerStr" />
      <el-table-column label="有效天数" align="center" prop="validDays" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.index" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)">修改
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" /> -->

    <!-- 修改 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body @close="cancel">

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <div> 算力名称：{{form.serverName}}</div>
        </el-col>
      </el-row>
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        <el-form-item label="最小奖励百分比" prop="minPerStr">
          <!-- <el-input v-model="form.minPerStr" placeholder="请输入最小奖励百分比" /> -->
          <el-input-number :min="0" v-model="form.minPerStr" placeholder="请输入最小奖励百分比" />
        </el-form-item>
        <el-form-item label="每轮增长百分比" prop="addPerStr">
          <!-- <el-input v-model="form.addPerStr" placeholder="请输入每轮增长百分比" /> -->
          <el-input-number :min="0" v-model="form.addPerStr" placeholder="请输入每轮增长百分比" />
        </el-form-item>
        <el-form-item label="最大奖励百分比" prop="maxPerStr">
          <!-- <el-input v-model="form.maxPerStr" placeholder="请输入最大奖励百分比" /> -->
          <el-input-number :min="0" v-model="form.maxPerStr" placeholder="请输入最大奖励百分比" />
        </el-form-item>
        <!-- <el-form-item label="交易额度" prop="cmkAmtLimit">
          <el-input v-model="form.cmkAmtLimit" placeholder="请输入交易额度" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  creativesz,
  creative,
  getOrder,
  complete,
  updateOrder,
  getAreaList,
  send,
  exportOrder,
  importTemplate,
} from "@/api/admin/order";
import { getToken } from "@/utils/auth";

export default {
  name: "Order",
  data() {
    return {
      requestUrl: this.$img.requestUrl,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false, //地址弹窗
      openAddr: false, //地址
      openCourier: false, //快递
      openOrderDetail: false, //订单详情
      openConplete: false, //收货弹窗
      // 查询参数
      status: "all",
      startMounth: "",
      endMounth: "",
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderStatus: null,
        orderNo: null,
        addrName: null,
        addrTel: null,
        userId: null,
        account: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      sendRules: {},
      courierRules: {
        courierCompany: [
          { required: true, message: "物流公司不能为空", trigger: "blur" },
        ],
        courierId: [
          { required: true, message: "物流单号不能为空", trigger: "blur" },
        ],
      },
      //表单校验
      rules: {
        rangePerStr: [{ required: true, message: "请输入加权分红百分比", trigger: "blur" }],
        // cmkAmtLimit: [{ required: true, message: "请输入交易额度", trigger: "blur" }]
      },
      addrRules: {
        addrName: [
          { required: true, message: "收件人名字不能为空", trigger: "blur" },
        ],
        addrTel: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        category1Id: [
          { required: true, message: "请选择一级地址", trigger: "blur" },
        ],
        category2Id: [
          { required: true, message: "请选择二级地址", trigger: "blur" },
        ],
        category3Id: [
          { required: true, message: "请选择三级地址", trigger: "blur" },
        ],
        addrInfo: [
          { required: true, message: "详细地址不能为空", trigger: "blur" },
        ],
      },
      list1: [], //一级分类数据
      list2: [], //二级分类数据
      list3: [], //三级分类数据
      cForm: {
        //收集相应的一级二级分类的id
        category1Id: "",
        category2Id: "",
        category3Id: "",
      },
      sendForm: {},
      open1: false,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/admin/order/importData",
      },
    };
  },
  created() {
    this.getList();
    // this.getCategory1List();
  },

  methods: {
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      creativesz().then(
        (response) => {
          // this.orderList = response.data;
          let arr = []
          response.data.forEach(element => {
            element.index = element.status + ''
            arr.push(element)
          });
          this.orderList = arr;
          this.loading = false;
        }
      );
    },

    // 用户状态修改
    handleStatusChange(row) {
      let that = this
      let text = row.index == "1" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '"协议ID：' + row.creativeId + '"吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return creative({
            creativeId: row.creativeId,
            minPerStr: row.minPerStr,
            addPerStr: row.addPerStr,
            maxPerStr: row.maxPerStr,
            status: row.index,
          });
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function (ref) {
          console.log(ref)
          row.index = row.index == "0" ? "1" : "0";
        });
    },
    handleEdit(row) {
      let that = this;
      this.open = true;
      that.form = row
      console.log(row)
    },
    // 取消按钮
    cancel() {
      (this.open = false), //地址弹窗
        (this.openAddr = false), //地址
        (this.openCourier = false), //快递
        (this.openOrderDetail = false), //订单详情
        (this.openConplete = false);
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    statusSwitch(tab) {
      const status = tab.name;
      let projectStatus = "";
      if (status === "all") {
        projectStatus = "";
      } else if (status === "unSend") {
        projectStatus = 0;
      } else if (status === "send") {
        projectStatus = 1;
      } else if (status === "complete") {
        projectStatus = 3;
      }
      this.queryParams.orderStatus = projectStatus;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    complete(row) {
      const self = this;
      this.$confirm("是否确认客户已经收到货?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          complete(row.orderNo).then((response) => {
            self.msgSuccess("收货成功");
            self.getList();
          });
        })
        .catch(function () { });
    },
    /** 地址提交按钮 */
    submitForm() {
      let that = this
      this.$refs["form"].validate((valid) => {
        if (valid) {
          creative({
            serverId: that.form.creativeId,
            minPerStr: that.form.minPerStr,
            addPerStr: that.form.addPerStr,
            maxPerStr: that.form.maxPerStr,
            status: that.form.status,
          }).then(res => {
            this.open = false;
            that.msgSuccess("修改成功");
            that.getList();
          })
        } else {
        }
      });
    },
    /** 修改地址按钮操作,回显地址数据*/
    handleUpdate(row) {
      this.reset();
      const id = row.orderNo;
      getOrder(id).then((response) => {
        this.form = response.data;
        this.form.category1Id = "";
        this.form.category2Id = "";
        this.form.category3Id = "";
        let addr = this.form.addrArea;
        this.cForm.category1Id = "";
        this.cForm.category2Id = "";
        this.cForm.category3Id = "";

        //回显三级地址
        var obj1 = {};
        var obj2 = {};
        var obj3 = {};
        let arr = addr.split(/\s+/);
        if (arr.length == 3) {
          let addr1 = arr[0];
          let addr2 = arr[1];
          let addr3 = arr[2];

          obj1 = this.list1.find(function (i) {
            return i.areaName === addr1;
          });
          if (typeof obj1 != "undefined") {
            this.form.category1Id = obj1.id;
            this.cForm.category1Id = obj1.id;
            getAreaList(obj1.id).then((response) => {
              this.list2 = response.data;
              obj2 = this.list2.find(function (i) {
                return i.areaName === addr2;
              });
              this.form.category2Id = obj2.id;
              this.cForm.category2Id = obj2.id;
              getAreaList(obj2.id).then((response) => {
                this.list3 = response.data;
                obj3 = this.list3.find(function (i) {
                  return i.areaName === addr3;
                });
                this.form.category3Id = obj3.id;
                this.cForm.category3Id = obj3.id;
                this.open = true;
                this.title = "修改收货地址";
              });
            });
          }
        }
      });
    },
    getCategory1List() {
      getAreaList(0).then((response) => {
        console.log(response, "地区");
        this.list1 = response.data;
      });
    },

    async handler1() {
      // 一级分类的select事件的回调（当一级分类的option发生变化时拿到对应二级分类的数据
      //清除数据
      this.list2 = [];
      this.list3 = [];
      this.cForm.category1Id = this.form.category1Id;
      this.cForm.category2Id = "";
      this.cForm.category3Id = "";
      let parentId = this.cForm.category1Id;
      getAreaList(parentId).then((response) => {
        this.list2 = response.data;
      });
    },
    async handler2() {
      // 二级分类的事件回调（当二级分类的option发生变化时拿到对应三级分类的数据
      //   清除三级分类的数据
      this.list3 = [];
      this.cForm.category2Id = this.form.category2Id;
      this.cForm.category3Id = "";
      getAreaList(this.cForm.category2Id).then((response) => {
        this.list3 = response.data;
      });
    },
    async handler3() {
      let parentId1 = this.cForm.category1Id;
      let parentId2 = this.cForm.category2Id;
      this.cForm.category3Id = this.form.category3Id;
      let parentId3 = this.cForm.category3Id;
      var obj1 = {};
      var obj2 = {};
      var obj3 = {};
      obj1 = this.list1.find(function (i) {
        return i.id === parentId1;
      });
      obj2 = this.list2.find(function (i) {
        return i.id === parentId2;
      });
      obj3 = this.list3.find(function (i) {
        return i.id === parentId3;
      });
      this.form.addrArea =
        obj1.areaName + " " + obj2.areaName + " " + obj3.areaName;
    },
    send(row) {
      this.reset1();
      this.title = "填写快递信息";
      this.open1 = true;
      this.sendForm.orderId = row.orderId;
    },
    reset1() {
      this.resetForm("sendForm");
    },
    cancel1() {
      this.reset1();
      this.open1 = false;
    },
    /** 地址提交按钮 */
    deliver() {
      this.$refs["sendForm"].validate((valid) => {
        if (valid) {
          if (this.sendForm.orderId != null) {
            send(this.sendForm).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("发货成功");
                this.open1 = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    handleDetail(row) {
      this.resetForm("form");
      const id = row.orderNo;
      getOrder(id).then((response) => {
        this.form = response.data;
        this.openOrderDetail = true;
        this.title = "查看订单详情";
      });
    },
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出订单数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportOrder(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () { });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "快递订单导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
